<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <!-- 搜索板块 -->
      <a-row class="row-item-search">
        <a-form class="search-form" :form="searchForm" layout="inline" @submit="handleSearch">
          <a-form-item label="名称">
            <a-input v-decorator="['name']" placeholder="请输入文件名称" />
          </a-form-item>
          <a-form-item class="search-btn">
            <a-button type="primary" icon="search" html-type="submit">搜索</a-button>
          </a-form-item>
        </a-form>

      </a-row>

      <!-- 操作板块 -->
      <div class="row-item-tab clearfix">
        <a-upload style='display: none' name="iFile" :accept="accept" :beforeUpload="beforeUpload"
          :customRequest="onUpload" :multiple="true" :showUploadList="false">
          <a-button icon="cloud-upload" ref='uploadBtn'>上传</a-button>
        </a-upload>
        <a-button icon="plus" class="fl-l" @click='onAdd({})' type="primary">新增分组</a-button>
      </div>
    </div>
    <s-table ref="table" rowKey="group_id" :loading="isLoading" :columns="columns" :data="loadData" :pageSize="15">

      <span slot='parentName' slot-scope='text'>
        {{ text || '-' }}
      </span>handleDelete
      <span class="actions" slot="action" slot-scope="text,item">
        <a @click='handleUploadFile(item.group_id)'>上传文件</a>
        <a style='color: red;' v-action:delete @click="handleDelete(item.group_id)">删除</a>
        <a v-action:edit @click='onAdd(item)'>编辑</a>
      </span>
    </s-table>
    <AddGroupForm ref="AddGroupForm" :groupList="groupList" @handleSubmit="handleRefresh" />
  </a-card>
</template>

<script>
import * as Api from '@/api/files/group'
import { STable } from '@/components'
import { image } from '@/api/upload'

import AddGroupForm from '@/components/Modal/FilesModal/AddGroupForm'

import { debounce } from '@/utils/util'
export default {
  name: 'Index',
  components: {
    STable, AddGroupForm

  },
  data() {
    return {
      accept: 'image/jpeg,image/png,image/gif,image/webp',
      // 当前表单元素
      searchForm: this.$form.createForm(this),
      groupList: [],
      // 查询参数
      queryParam: {},
      uploadSizeLimit: 2,
      // 正在加载
      isLoading: false,
      // 表头
      columns: [
        {
          title: '分组名称',
          dataIndex: 'name'
        },
        {
          title: '上级名称',
          dataIndex: 'parentName',
        },
        {
          title: '文件数量',
          dataIndex: 'fileNum',
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: param => {
        return Api.listWithPage({ ...param, ...this.queryParam })
          .then(response => response.data.list)
      },
      groupId: '',
      // 上传中的文件
      uploading: []
    }
  },
  created() {

  },
  methods: {

    // 确认搜索
    handleSearch(e) {
      e.preventDefault()
      this.searchForm.validateFields((error, values) => {
        if (!error) {
          this.queryParam = { ...this.queryParam, ...values }
          this.handleRefresh(true)
        }
      })
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh(bool = false) {
      this.$refs.table.refresh(bool)
    },


    onAdd(item) {
      this.isLoading = true
      Api.list({}).then(result => {
        // 记录列表数据
        this.groupList = result.data.list
        // console.log(this.groupList)
        setTimeout(() => {
          this.$refs.AddGroupForm.add(item)
        }, 300)
      }).finally(() => {
        this.isLoading = false
      })
    },
    handleUploadFile(groupId) {
      this.groupId = groupId
      this.$refs.uploadBtn.$el.click()
    },
    // 事件: 上传文件之前
    beforeUpload(file, fileList) {
      // 显示错误提示(防抖处理)
      const showErrorMsg = debounce(this.$message.error, 20)
      // 验证文件大小
      const fileSizeMb = file.size / 1024 / 1024
      if (fileSizeMb > this.uploadSizeLimit) {
        showErrorMsg(`上传的文件大小不能超出${this.uploadSizeLimit}MB`)
        return false
      }
      return true
    },
    // 事件: 自定义上传
    onUpload(info) {
      this.isLoading = true
      // 记录上传状态
      this.uploading.push(true)
      // 构建上传参数
      const formData = new FormData()
      formData.append('iFile', info.file)
      formData.append('groupId', this.groupId)
      // 开始上传
      image(formData)
        .finally(() => {
          this.uploading.pop()
          if (this.uploading.length === 0) {
            this.isLoading = false
            this.handleRefresh(true)
          }
        })
    },

    handleDelete(groupId) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要删除该记录吗?',
        content: '删除后不可恢复',
        onOk() {
          return Api.deleted({ groupId })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally(result => modal.destroy())
        }
      })
    },
  }
}
</script>

<style lang="less" scoped>
.ant-card-body {
  padding: 22px 29px 25px;
}
</style>
